package org.i1510.common.service.CxfInterceptor;

import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPMessage;

import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.binding.soap.saaj.SAAJInInterceptor;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.i1510.common.enums.CxfSoapHeaderAuth;
import org.i1510.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.NodeList;

import sun.util.logging.resources.logging;

public class SoapHeaderAuthIntercetpr extends
		AbstractPhaseInterceptor<SoapMessage> {
	private static final Logger logger = LoggerFactory
			.getLogger(SoapHeaderAuthIntercetpr.class);
	private SAAJInInterceptor saa = new SAAJInInterceptor();

	public SoapHeaderAuthIntercetpr() {
		super(Phase.PRE_INVOKE);
		getAfter().add(SAAJInInterceptor.class.getName());
	}

	@Override
	public void handleMessage(SoapMessage message) throws Fault {
		SOAPMessage mess = message.getContent(SOAPMessage.class);
		if (mess == null) {
			saa.handleMessage(message);
			mess = message.getContent(SOAPMessage.class);
		}
		try {
			SOAPHeader head = mess.getSOAPHeader();
			if (head == null) {
				return;
			}
			// 读取自定义的节点
			NodeList nodes = head.getElementsByTagName("tns:spUserName");
			NodeList nodepass = head.getElementsByTagName("tns:spPassword");
			NodeList nodetype = head.getElementsByTagName("tns:spAuthType");
			// 获取节点值，简单认证
			switch (StringUtils.String2Integer(nodetype.item(0)
					.getTextContent().trim())) {
			case 1:
				logger.info(CxfSoapHeaderAuth.LEVEL1.getValue()
						+ CxfSoapHeaderAuth.ACCESSYES.getValue());
				break;
			case 2:
				if (nodes.item(0).getTextContent().equals(CxfSoapHeaderAuth.USERNAME.getValue())) {
					if (nodepass.item(0).getTextContent().equals(CxfSoapHeaderAuth.PASSWORD.getValue())) {
						logger.info(CxfSoapHeaderAuth.LEVEL2.getValue()
								+ CxfSoapHeaderAuth.ACCESSYES.getValue());
					}else{
						SOAPException soapExc = new SOAPException(
								CxfSoapHeaderAuth.LEVEL2.getValue()
										+ CxfSoapHeaderAuth.ACCESSNOT.getValue());
						throw new Fault(soapExc);
					}
				} else {
					SOAPException soapExc = new SOAPException(
							CxfSoapHeaderAuth.LEVEL2.getValue()
									+ CxfSoapHeaderAuth.ACCESSNOT.getValue());
					throw new Fault(soapExc);
				}
				break;

			default:
				SOAPException soapExc = new SOAPException(
						CxfSoapHeaderAuth.ACCESSNOT.getValue());
				throw new Fault(soapExc);
			}

		} catch (SOAPException e) {
			e.printStackTrace();
		} catch (Exception e) {
			SOAPException soapExc = new SOAPException(
					CxfSoapHeaderAuth.ACCESSNOT.getValue());
			throw new Fault(soapExc);
		}
	}
}